import 'package:love_newf/value/app_colors.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_style.dart';

class VerificationCodeCustom extends StatefulWidget {
  ///验证码数组
  final Function(String code) textChanged;

  ///itemCount 验证码长度：4或6，默认是6
  final int itemCount;

  ///是否自动获取焦点
  final autofocus;
  String code;

  List<FocusNode> focusNodeList = [];
  List<String> textList = [];

  VerificationCodeCustom(
      {required this.textChanged,
      required this.code,
      this.itemCount = 4,
      this.autofocus = true}) {
    focusNodeList.clear();
    textList.clear();
    for (int i = 0; i < itemCount; i++) {
      FocusNode focusNode = FocusNode();
      focusNodeList.add(focusNode);
      textList.add('');
    }
  }

  @override
  _VerificationCodeCustomState createState() =>
      _VerificationCodeCustomState(this.textChanged, this.itemCount);
}

class _VerificationCodeCustomState extends State<VerificationCodeCustom> {
  Function textChanged;
  final int itemCount;

  // String code;

  _VerificationCodeCustomState(this.textChanged, this.itemCount);

  final double width = 46.w;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // textList.clear();
    // for (int i = 0; i < itemCount; i++) {
    //   if (widget.code.length > i + 1) {
    //     textList.add(widget.code[i]);
    //   } else {
    //     textList.add('');
    //   }
    // }
    // if (widget.code.trim().isEmpty && !focusNodeList[0].hasFocus) {
    //   _getFocus(focusNodeList[0]);
    // }
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 52.w,
      child: Stack(
        children: [
          Row(children: _textFieldList()),
          GestureDetector(
            onTap: () {
              for (int i = 0; i < widget.textList.length; i++) {
                if (widget.textList[i].trim().isEmpty) {
                  _getFocus(widget.focusNodeList[i]);
                  break;
                }
              }
            },
            child: Container(
                color: Colors.transparent,
                height: 52.w,
                width: double.infinity),
          )
        ],
      ),
    );
  }

  _textFieldList() {
    List<Widget> list = [];
    for (int i = 0; i < 6; i++) {
      list.add(LExpand(
        child: Container(
            alignment: Alignment.center,
            child: _textField(i, widget.textList[i], widget.focusNodeList[i])),
      ));
    }

    return list;
  }

  _textField(int index, String text, FocusNode focusNode) {
    TextEditingController _controller = TextEditingController(text: text);
    _controller.selection = TextSelection.fromPosition(
        TextPosition(affinity: TextAffinity.downstream, offset: text.length));

    return LContainer(
      lStyle: LStyle(
        width: 46.w,
        height: 52.w,
        backgroundColor: AppColors.bgDisableColor,
        radius: 12.w,
      ),
      child: TextField(
        controller: _controller,
        focusNode: focusNode,
        // autofocus: index == 0 ? widget.autofocus : false,
        textAlign: TextAlign.start,
        decoration: InputDecoration(
            isCollapsed: true,
            contentPadding: EdgeInsets.only(top: 8.w, left: 15.w),
            border: InputBorder.none),
        // scrollPadding: EdgeInsets.all(200),
        // textAlign: TextAlign.center,
        style: TextStyle(
            color: const Color(0xFF181818),
            fontSize: 24.sp,
            fontWeight: FontWeight.w800),
        keyboardType: TextInputType.number,
        onChanged: (value) {
          if (value.length > 1) {
            if (value.substring(0, 1) == ' ') {
              value = value.substring(1, value.length);
            }
          }
          //输入非数字，不变
          if (!RegExp('^[0-9]*\$').hasMatch(value)) {
            setState(() {});
            return;
          } else {}

          String oldStr = widget.textList[index];

          //输入值为复制的验证码
          if (value.length == itemCount || value.length == itemCount + 1) {
            if (value.length == itemCount + 1) {
              if (oldStr == value.substring(0, 1)) {
                //删除第一位
                value = value.substring(1);
              } else {
                //删除最后一位
                value = value.substring(0, value.length - 1);
              }
            }

            //所有重新赋值
            for (int i = 0; i < widget.textList.length; i++) {
              widget.textList[i] = value.substring(i, i + 1);
            }
            _loseFocus(widget.focusNodeList[index]);
            setState(() {});
            textChangedformat(widget.textList);
            return;
          }

          //删除字符
          if (value.length == 0) {
            //焦点前移
            if (index > 0) {
              if (index == widget.textList.length - 1) {
                //最后一位
                if (widget.textList[index] == ' ') {
                  _getFocus(widget.focusNodeList[index - 1]);
                  widget.textList[index - 1] = ' ';
                }
              } else {
                _getFocus(widget.focusNodeList[index - 1]);
                widget.textList[index - 1] = ' ';
              }
            }
            widget.textList[index] = ' ';

            setState(() {});
            textChangedformat(widget.textList);
          } else {
            //赋值
            widget.textList[index] = value;
            //焦点后移
            if (index < widget.focusNodeList.length - 1) {
              _getFocus(widget.focusNodeList[index + 1]);
              widget.textList[index + 1] = ' ';
            } else {
              _loseFocus(widget.focusNodeList[index]);
            }
            setState(() {});
            textChangedformat(widget.textList);
          }
        },
      ),
    );
  }

  void textChangedformat(List<String> a) {
    String code = "";
    for (String c in a) {
      code += c;
    }
    // this.code = code;
    textChanged(code);
  }

  ///获取焦点
  _getFocus(FocusNode focusNode) async {
    if (!focusNode.hasFocus) {
      FocusScope.of(context).requestFocus(focusNode);
    } else {
      _loseFocus(focusNode);
      Future.delayed(const Duration(milliseconds: 100), () {
        FocusScope.of(context).requestFocus(focusNode);
      });
    }
  }

  ///失去焦点
  _loseFocus(FocusNode focusNode) {
    focusNode.unfocus();
  }
}
